//
//  JDAllOrderListViewController.swift
//  DragonWallet
//
//  Created by volantPig on 2025/5/18.
//

import UIKit
import JXSegmentedView
import ProgressHUD

class JDAllOrderListViewController: JDBaseViewController {

    var baseVC: UIViewController?
    var mainTableView: UITableView?
    var orderListModels: [JDOrderListModel?]?
    
    var isFirstLoad: Bool = true
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if self.isFirstLoad == false {
            self.getNetData(true)
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.view.backgroundColor = .commonColor()
        self.setupUIElements()
        self.getNetData()
        self.isFirstLoad = false

        // Do any additional setup after loading the view.
    }
    
    func setupUIElements() {
        
        self.mainTableView = UITableView(frame: .zero, style: .plain)
        self.view.addSubview(self.mainTableView!)
        self.mainTableView?.snp.makeConstraints({ make in
            make.left.right.equalTo(self.view)
            make.top.equalTo(self.view)
            make.bottom.equalTo(self.view).offset(-UIDevice().safeAreaInset.top)
        })
        self.mainTableView?.delegate = self
        self.mainTableView?.dataSource = self
        self.mainTableView?.register(JDOrderTableViewCell.self, forCellReuseIdentifier: "myCell")
        self.mainTableView?.register(JDOrderListReleaseCell.self, forCellReuseIdentifier: "releaseCell")
        
        self.mainTableView?.backgroundColor = self.commonColor
        self.mainTableView?.separatorStyle = .none
        
        self.mainTableView?.addRefreshHeader { [weak self] in
            self?.currentPage = 1
            self?.getNetData(true)
        }
        
        self.mainTableView?.addRefreshFooter { [weak self] in
            self?.currentPage += 1
            self?.getNetData(false)
        }
    }
    
    override func getNetData(_ isRefresh: Bool = true) {
        
        var params = [String: Any]()
        params["status"] = 1
        params["pageNumber"] = self.currentPage
        params["pageSize"] = 10

        JDNetWorkRequest(.getOrderList(params)) { responseStr in
            
            printLog("待付款--订单列表:\(responseStr)")
            
            let commonModel = JDCommonModel.deserialize(from: responseStr, designatedPath: "")
            if commonModel?.code == "0" {
                if let models = [JDOrderListModel].deserialize(from: responseStr, designatedPath: "data.records") {
                    
                    if isRefresh {
                        self.orderListModels = models
                    } else {
                        self.orderListModels?.append(contentsOf: models)
                    }
                }
            }
            self.mainTableView?.reloadData()
            self.mainTableView?.endRefresh()
            
        } failure: { error in
            self.mainTableView?.reloadData()
            self.mainTableView?.endRefresh()
        } error: { errorCode in
            self.mainTableView?.reloadData()
            self.mainTableView?.endRefresh()
        }
        
    }

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}

/// cell上可能存在的事件
extension JDAllOrderListViewController {
    
    @objc func cancelOrderAction(_ button: UIButton) {
        
        self.showConfirmView("是否确认取消订单？") { [weak self] in
            let currentModel = self?.orderListModels?[button.tag]
            self?.cancelOrderRequest(orderId: currentModel?.orderId)
        }
        
    }
    
    func cancelOrderRequest(orderId: String?) {
        var params = [String: Any]()
        params["orderId"] = orderId
        ProgressHUD.animate()
        JDNetWorkRequest(.cancelOrder(params)) { responseStr in
            ProgressHUD.dismiss()
            let commonModel = JDCommonModel.deserialize(from: responseStr, designatedPath: "")
            if commonModel?.code == "0" {
                self.view.toast(message: "删除成功")
                self.currentPage = 1
                self.getNetData(true)
            } else {
                self.view.toast(message: commonModel?.msg ?? "")
            }

        } failure: { error in
            self.view.toast(message: error.localizedDescription)
            ProgressHUD.dismiss()
        } error: { errorCode in
            self.view.toast(message: "网络错误:\(errorCode)")
            ProgressHUD.dismiss()
        }
    }
    
    @objc func payOrderAction(_ button: UIButton) {
        let currentModel = self.orderListModels?[button.tag]
        
        
        if currentModel?.orderSaleType == "3" || currentModel?.orderSaleType == "4" || currentModel?.orderSaleType == "5" {
            //  龙看板样式
            let simpleOrderVC = JDSimpleOrderDetailViewController()
            simpleOrderVC.orderType = .waitingPay
            simpleOrderVC.orderId = currentModel?.orderId
            self.baseVC?.hidesBottomBarPushViewController(simpleOrderVC)
        } else {
            let newOrderDetailVC = JDNewOrderDetailViewController()
            newOrderDetailVC.shopName = currentModel?.shopName
            newOrderDetailVC.orderType = .waitingPay
            newOrderDetailVC.orderId = currentModel?.orderId
            self.baseVC?.hidesBottomBarPushViewController(newOrderDetailVC)
        }
    }
    
    @objc func changeAddress(_ button: UIButton) {
        print("修改地址:\(button.tag)")
    }
    
    @objc func moreButtonAction(_ button: UIButton) {
        print("更多按钮:\(button.tag)")
    }
    
    /// 查看物流
    @objc func checkLogistics(_ button: UIButton) {
        let currentModel = self.orderListModels?[button.tag]
        print("查看物流:\(button.tag)")
        let deliveryInfoVC = JDDeliveryInfoViewController()
        self.hidesBottomBarPushViewController(deliveryInfoVC)
    }
    
}

extension JDAllOrderListViewController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.orderListModels?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
//        orderListModels
        
        let currentModel = self.orderListModels?[indexPath.row]
        if currentModel?.orderSaleType == "3" || currentModel?.orderSaleType == "4" || currentModel?.orderSaleType == "5" {
            // 发布
            let releaseCell = tableView.dequeueReusableCell(withIdentifier: "releaseCell") as? JDOrderListReleaseCell
            releaseCell?.orderType = .waitingPay
            releaseCell?.orderModel = currentModel
            
//            releaseCell?.cancelButton?.addTarget(self, action: #selector(cancelOrderAction(_:)), for: .touchUpInside)
//            releaseCell?.cancelButton?.tag = indexPath.row
//            
//            releaseCell?.payButton?.addTarget(self, action: #selector(payOrderAction(_:)), for: .touchUpInside)
            
            return releaseCell!
        } else {
            
//            //    BUYER_PENDING_PAYMENT(1, "买家待付款"),
//            //        UNPAID_AUTO_CANCEL(2, "未付款自动取消"),
//            //        PAID_PENDING_ORDER(3, "已付款（待接单）"),
//            //        BUYER_MANUAL_CANCEL(4, "买家手动取消"),
//            //        MERCHANT_ACCEPTED_ORDER(5, "商家已接单"),
//            //        MERCHANT_REJECTED_ORDER(6, "商家已拒单"),
//            //        MERCHANT_SHIPPED(7, "商家已发货"),
//            //        LOGISTICS_ARRIVED(8, "物流已到货"),
//            //        BUYER_CONFIRM_RECEIPT(9, "买家确认收货"),
//            //        GOODS_PURCHASED(10, "商品已采购"),
//                var orderStatus: Int?
            
            
            // 其他
            let cell = tableView.dequeueReusableCell(withIdentifier: "myCell") as? JDOrderTableViewCell

//            let currentModel = self.orderListModels?[indexPath.row]
            
            if currentModel?.orderStatus == 1 {
                cell?.orderType = .waitingPay
                // 买家待付款
                cell?.cancelButton?.addTarget(self, action: #selector(cancelOrderAction(_:)), for: .touchUpInside)
                cell?.cancelButton?.tag = indexPath.row
                cell?.payButton?.addTarget(self, action: #selector(payOrderAction(_:)), for: .touchUpInside)
                cell?.payButton?.tag = indexPath.row
                cell?.moreButton?.addTarget(self, action: #selector(moreButtonAction(_:)), for: .touchUpInside)
                cell?.moreButton?.tag = indexPath.row
            } else if currentModel?.orderStatus == 2 || currentModel?.orderStatus == 4 {
                cell?.orderType = .cancel
                // 未付款自动取消
            } else if currentModel?.orderStatus == 3  || currentModel?.orderStatus == 5 {
                cell?.orderType = .alreadyPay
                cell?.cancelButton?.addTarget(self, action: #selector(changeAddress(_:)), for: .touchUpInside)
                cell?.cancelButton?.tag = indexPath.row
                // 已付款（待接单） , 商家已接单
            } else if currentModel?.orderStatus == 7 || currentModel?.orderStatus == 8 {
                cell?.orderType = .pickup
                // 商家已发货 , 物流已到货
                cell?.cancelButton?.addTarget(self, action: #selector(checkLogistics(_:)), for: .touchUpInside)
                cell?.cancelButton?.tag = indexPath.row
            } else if currentModel?.orderStatus == 6 {
                // 商家已拒单
                cell?.orderType = .refusse
            } else if currentModel?.orderStatus == 9 {
                // 交易完成
                cell?.orderType = .completed
                cell?.cancelButton?.addTarget(self, action: #selector(checkLogistics(_:)), for: .touchUpInside)
                cell?.cancelButton?.tag = indexPath.row
            }
            cell?.orderModel = currentModel
            
            return cell!
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        printLog("代付款->点击:\(indexPath.row)")
        let currentModel = self.orderListModels?[indexPath.row]
        
        if currentModel?.orderSaleType == "3" || currentModel?.orderSaleType == "4" || currentModel?.orderSaleType == "5" {
            //  龙看板样式
            let simpleOrderVC = JDSimpleOrderDetailViewController()
            simpleOrderVC.orderType = .waitingPay
            simpleOrderVC.orderId = currentModel?.orderId
            self.baseVC?.hidesBottomBarPushViewController(simpleOrderVC)
        } else {
            let newOrderDetailVC = JDNewOrderDetailViewController()
            newOrderDetailVC.shopName = currentModel?.shopName
            
            
            if currentModel?.orderStatus == 1 {
                newOrderDetailVC.orderType = .waitingPay
            } else if currentModel?.orderStatus == 2 || currentModel?.orderStatus == 4 {
                newOrderDetailVC.orderType = .cancel
                // 未付款自动取消
            } else if currentModel?.orderStatus == 3  || currentModel?.orderStatus == 5 {
                newOrderDetailVC.orderType = .alreadyPay
                // 已付款（待接单） , 商家已接单
            } else if currentModel?.orderStatus == 7 || currentModel?.orderStatus == 8 {
                newOrderDetailVC.orderType = .pickup
                // 商家已发货 , 物流已到货
            } else if currentModel?.orderStatus == 6 {
                // 商家已拒单
                newOrderDetailVC.orderType = .refusse
            } else if currentModel?.orderStatus == 9 {
                // 交易完成
                newOrderDetailVC.orderType = .completed
            }
            newOrderDetailVC.orderId = currentModel?.orderId
            self.baseVC?.hidesBottomBarPushViewController(newOrderDetailVC)
            
//            let orderDetailVC = JDOrderDetailViewController()
//            orderDetailVC.simpleCallBack = { [weak self] in
//                self?.currentPage = 1
//                self?.getNetData(true)
//            }
//            orderDetailVC.shopName = currentModel?.shopName
//            orderDetailVC.orderId = currentModel?.orderId
//            orderDetailVC.orderType = .waitingPay
//            self.baseVC?.hidesBottomBarPushViewController(orderDetailVC)
        }
    }
    
}


extension JDAllOrderListViewController: JXSegmentedListContainerViewListDelegate {
    func listView() -> UIView {
        return self.view
    }
}
